package saxion.speelveld.spaceengineer.controller;

import saxion.speelveld.spaceengineer.R;
import saxion.speelveld.spaceengineer.model.Game;
import saxion.speelveld.spaceengineer.model.Resource;
import saxion.speelveld.spaceengineer.model.ResourceType;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ResourceSimpleAdapter extends ArrayAdapter<Resource>
{
	private Context context;

	private Resource[] resources;

	private Game game;

	public ResourceSimpleAdapter(Context context, Game game)
	{
		super(context, R.layout.resource_item_layout, game.getViewableResourceArray());
		this.init(context, game);
	}

	private void init(Context context, Game game)
	{
		this.context = context;
		this.resources = game.getViewableResourceArray();
		this.game = game;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		convertView = inflater.inflate(R.layout.resource_item_layout, parent, false);

		TextView textView = (TextView) convertView.findViewById(R.id.tv_resource_label);
		ImageView imageView = (ImageView) convertView.findViewById(R.id.iv_resource_image);
		TextView tvGainsPerTick = (TextView) convertView.findViewById(R.id.tvResourceGainPerTick);
		TextView tvCostsPerTick = (TextView) convertView.findViewById(R.id.tvResourceCostPerTick);

		Bitmap resourceImage = null;
		try
		{
			resourceImage = BitmapManager.getBitmapByResourceType(resources[position].getResourceType(), context);
		}
		catch (Exception ex)
		{

		}

		if (resourceImage != null)
		{
			imageView.setImageBitmap(resourceImage);
		}
		if (resources[position].getResourceType() == ResourceType.HAPPINESS)
		{
			textView.setText(resources[position].toStringCurrentValueWithMaxValue(100));
		}
		else if (resources[position].getResourceType() == ResourceType.POPULATION)
		{
			textView.setText(resources[position].toStringCurrentValueWithMaxValue(game
				.getResourceAmount(ResourceType.POPULATIONCAP)));
		}
		else
		{
			textView.setText(resources[position].toStringCurrentValueWithMaxValue(game
				.getResourceAmount(ResourceType.STORAGESPACE)));
		}
		if (resources[position].getAmountGainPerTick() > 0)
		{
			tvGainsPerTick.setText("+" + resources[position].getAmountGainPerTick());
		}
		if (resources[position].getAmountCostPerTick() > 0)
		{
			tvCostsPerTick.setText("-" + resources[position].getAmountCostPerTick());
			tvGainsPerTick.setPadding(0, 0, 6, 0);

		}

		return convertView;
	}
}
